package net.wicp.tams.commons.binlog.replication.down;

import java.io.IOException;

import org.apache.tapestry5.json.JSONObject;

import net.wicp.tams.commons.apiext.ByteUtil;
import net.wicp.tams.commons.apiext.ByteUtil.AssitRead;
import net.wicp.tams.commons.binlog.bean.PacketBean;
import net.wicp.tams.commons.binlog.constant.StatusFlags;
import net.wicp.tams.commons.io.UnsignedLong;

public class OKPacket extends AbsResultPacket {
	private static final long serialVersionUID = 1L;
	public static final byte PACKET_MARKER = (byte) 0x00;

	private int packetMarker;
	private UnsignedLong affectedRows;
	private UnsignedLong insertId;
	private StatusFlags serverStatus;
	private int warningCount;
	private String message;

	public OKPacket(PacketBean packetBean) {
		super(packetBean);
	}

	@Override
	protected void readBody(AssitRead reader) throws IOException {
		packetMarker = ByteUtil.readIntL(reader.readBytes(1));
		affectedRows = reader.readUnsignedLong();
		insertId = reader.readUnsignedLong();
		serverStatus = StatusFlags.get(ByteUtil.readIntL(reader.readBytes(2)));
		warningCount = ByteUtil.readIntL(reader.readBytes(2));
		if (reader.hasMore())
			message = ByteUtil.readString(reader.readRest());
	}

	public int getPacketMarker() {
		return packetMarker;
	}

	public UnsignedLong getAffectedRows() {
		return affectedRows;
	}

	public UnsignedLong getInsertId() {
		return insertId;
	}

	public StatusFlags getServerStatus() {
		return serverStatus;
	}

	public int getWarningCount() {
		return warningCount;
	}

	public String getMessage() {
		return message;
	}

	@Override
	public JSONObject getBody() {
		JSONObject retobj = new JSONObject("affectedRows", affectedRows.intValue(), "insertId", insertId.intValue(),
				"serverStatus", serverStatus.name(), "warningCount", warningCount, "message", message);
		return retobj;
	}

	@Override
	public boolean isSuc() {
		return true;
	}

}
